package org.ziegler.log.analysis;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.commons.lang3.math.NumberUtils;

public class AppConfig {

    private static final AppConfig APP_CONFIG = new AppConfig();
    public static AppConfig getInstance() {

        return APP_CONFIG;
    }

    private String logPath;

    private int threadPoolNum;

    public void init() {
        File configDir = new File("./config");
        if (!configDir.exists()) {
            configDir.mkdir();
        }

        File file = new File(ConstUtils.PROP_FILENAME);
        if (!file.exists()) {
            logPath = "";
            threadPoolNum = 16;
            APP_CONFIG.save();
        }

        APP_CONFIG.load();
    }

    private void load() {
        // 读取
        Properties prop = new Properties();//属性集合对象
        try {
            final FileInputStream in = new FileInputStream(ConstUtils.PROP_FILENAME);
            prop.load(in);

            logPath = prop.getProperty("path");
            threadPoolNum = NumberUtils.toInt(prop.getProperty("threadNum"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void save() {
        // 创建文件
        Properties prop = new Properties();
        try {
            OutputStream out = new FileOutputStream(ConstUtils.PROP_FILENAME);
            prop.setProperty("path", logPath);
            prop.setProperty("threadNum", String.valueOf(threadPoolNum));

            prop.store(out, "aaa");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String getLogPath() {
        return logPath;
    }

    public void setLogPath(String logPath) {
        this.logPath = logPath;
        LogCore.debug("属性文件更新logPath = " + logPath);
        save();
    }

    public int getThreadPoolNum() {
        return threadPoolNum;
    }

    public void setThreadPoolNum(int threadPoolNum) {
        this.threadPoolNum = threadPoolNum;
        LogCore.debug("属性文件更新threadPoolNum = " + threadPoolNum);
        save();
    }
}
